
package com.netease.xone.widget.msgbubble;

import org.jbox2d.collision.shapes.ChainShape;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;

public class Box2dBase {

    private World mWorld;

    public Box2dBase() {
        mWorld = new World(new Vec2(0, 0f));
    }

    public World getWorld() {
        return mWorld;
    }

    /**
     * 清除重力
     */
    public void clearGravity() {
        mWorld.setGravity(new Vec2(0f, 0f));
    }

    /**
     * 创建一个圆
     * 
     * @param x
     * @param y
     * @param radius
     * @param isStatic
     * @return
     */
    public Body createCircle(float x, float y, float radius, boolean isStatic) {
        BodyDef bDef = new BodyDef();
        if (!isStatic) {
            bDef.type = BodyType.DYNAMIC;
        } else {
            bDef.type = BodyType.STATIC;
        }
        bDef.position.set(x, y);
        Body circle = getWorld().createBody(bDef);

        FixtureDef fDef = new FixtureDef();
        if (!isStatic) {
            fDef.density = 1;
            fDef.restitution = 1f;
            fDef.friction = 0f;
        } else {
            fDef.density = 0;
        }
        CircleShape shape = new CircleShape();
        shape.m_radius = radius;
        fDef.shape = shape;

        circle.createFixture(fDef);
        return circle;
    }

    /**
     * 使用ChainShape创建墙壁
     * 
     * @param startX
     * @param startY
     * @param endX
     * @param endY
     * @return
     */
    public Body createWall(float startX, float startY, float endX, float endY) {
        BodyDef bDef = new BodyDef();
        bDef.type = BodyType.STATIC;
        bDef.position.set(startX, startY);
        Body wall = getWorld().createBody(bDef);
        ChainShape shape = new ChainShape();
        Vec2[] vertices = new Vec2[4];
        vertices[0] = new Vec2(startX, startY);
        vertices[1] = new Vec2(endX, startY);
        vertices[2] = new Vec2(endX, endY);
        vertices[3] = new Vec2(startX, endY);
        shape.createLoop(vertices, 4);
        if (wall != null)
            wall.createFixture(shape, 4);
        return wall;
    }

}
